import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { EntityManager, Repository } from 'typeorm';
import { DEFAULT_PAGE_SIZE } from '../config/contants';

import { TbOrder } from '../entities/TbOrder';

@Injectable()
export class OrderModel {
  constructor(
    @InjectRepository(TbOrder)
    private readonly tbOrderRepository: Repository<TbOrder>,
  ) {}

  // 查询订单列表
  async getOrderList(
    userAddress: string,
    orderNo: string,
    sellerAddress: string,
    assetAddress: string,
    assetType: number,
    limit: number,
    offset: number,
  ): Promise<[TbOrder[], number]> {
    if (!offset || offset < 0) {
      offset = 0;
    }

    if (!limit || limit < 1) {
      limit = DEFAULT_PAGE_SIZE;
    }

    let where: any = { userAddress };
    if (orderNo != '') {
      where.orderNo = orderNo;
    }
    if (sellerAddress != '') {
      where.sellerAddress = sellerAddress;
    }
    if (assetAddress != '') {
      where.assetAddress = assetAddress;
    }
    if (assetType > 0) {
      where.assetType = assetType;
    }

    return await this.tbOrderRepository.findAndCount({
      where,
      skip: offset,
      take: limit,
      order: {
        id: 'DESC',
      },
    });
  }

  // 查询订单详情
  async getOrderById(id: number): Promise<TbOrder> {
    return await this.tbOrderRepository.findOne({
      where: {
        id,
      },
    });
  }

  async getOrderByOrderNo(orderNo: string): Promise<TbOrder> {
    return await this.tbOrderRepository.findOne({
      where: {
        orderNo,
      },
    });
  }

  // 增加或保存订单
  async saveOrder(data: any, manager: EntityManager = null): Promise<TbOrder> {
    if (!data.id || data.id == 0) {
      data.createdAt = new Date();
    }
    data.updatedAt = new Date();

    try {
      if (manager) {
        return await manager.save(data); // 便于在事务中执行
      } else {
        return await this.tbOrderRepository.save(data);
      }
    } catch (error) {
      console.error('delOrder error:', error);
      throw error;
    }

    // 执行原生sql
    // await this.tbOrderRepository.query('UPDATE tb_order SET is_deleted=1 where id=1');
  }

  // 删除订单
  async removeOrder(id: number, manager: EntityManager = null): Promise<void> {
    let where: any = {
      id,
    };
    try {
      if (manager) {
        await manager.update(TbOrder, where, { isDeleted: 1 });
      } else {
        await this.tbOrderRepository.update(where, { isDeleted: 1 });
      }
    } catch (error) {
      console.error('delOrder error:', error);
      throw error;
    }
  }
}
